import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';

// 所有城市列表
const allCities = [
  '北京', '上海', '广州', '深圳', '天津', '重庆', '石家庄', '太原', '沈阳', '长春',
  '哈尔滨', '南京', '杭州', '合肥', '福州', '南昌', '济南', '郑州', '武汉', '长沙',
  '广州', '南宁', '海口', '成都', '贵阳', '昆明', '西安', '兰州', '西宁', '银川',
  '乌鲁木齐', '呼和浩特', '大连', '青岛', '宁波', '厦门', '珠海', '汕头', '佛山',
  '东莞', '中山', '烟台', '威海', '徐州', '常州', '扬州', '泉州', '温州', '绍兴',
  '嘉兴', '湖州', '金华', '台州', '盐城', '镇江', '泰州', '马鞍山', '芜湖', '蚌埠',
  '潍坊', '济宁', '淄博', '临沂', '洛阳', '开封', '许昌', '株洲', '岳阳', '常德',
  '惠州', '江门', '茂名', '韶关', '肇庆', '梧州', '柳州', '桂林', '北海', '泸州',
  '德阳', '绵阳', '遵义', '丽江', '咸阳', '宝鸡', '天水', '克拉玛依', '石嘴山'
];

// 热门城市
const hotCities = [
  '北京', '上海', '重庆', '广州',
  '杭州', '南京', '成都', '深圳',
  '西安', '天津', '武汉', '深圳'
];

export default function Location() {
  const navigate = useNavigate();
  const [searchText, setSearchText] = useState('');
  const [currentCity, setCurrentCity] = useState('重庆');

  // 自动按字母分类城市
  const cityData = useMemo(() => {
    const data: { [key: string]: string[] } = {};
    
    // 对所有城市进行分类
    allCities.forEach(city => {
      const firstChar = city.charAt(0);
      // 获取首字符的拼音首字母（这里简化处理，实际项目中可以使用拼音库）
      let letter = firstChar;
      
      // 简单的汉字转拼音首字母映射（实际项目中建议使用专业的拼音库）
      const pinyinMap: { [key: string]: string } = {
        '北': 'B', '上': 'S', '广': 'G', '深': 'S', '天': 'T',
        '重': 'C', '石': 'S', '太': 'T', '沈': 'S', '长': 'C',
        '哈': 'H', '南': 'N', '杭': 'H', '合': 'H', '福': 'F',
        '济': 'J', '郑': 'Z', '武': 'W', '成': 'C', '贵': 'G',
        '昆': 'K', '西': 'X', '兰': 'L', '银': 'Y', '乌': 'W',
        '呼': 'H', '大': 'D', '青': 'Q', '宁': 'N', '厦': 'X',
        '珠': 'Z', '汕': 'S', '佛': 'F', '东': 'D', '中': 'Z',
        '烟': 'Y', '威': 'W', '徐': 'X', '常': 'C', '扬': 'Y',
        '泉': 'Q', '温': 'W', '绍': 'S', '嘉': 'J', '湖': 'H',
        '金': 'J', '台': 'T', '盐': 'Y', '镇': 'Z', '泰': 'T',
        '马': 'M', '芜': 'W', '蚌': 'B', '潍': 'W', '淄': 'Z',
        '临': 'L', '洛': 'L', '开': 'K', '许': 'X', '株': 'Z',
        '岳': 'Y', '惠': 'H', '江': 'J', '茂': 'M', '韶': 'S',
        '肇': 'Z', '梧': 'W', '柳': 'L', '桂': 'G', '泸': 'L',
        '德': 'D', '绵': 'M', '遵': 'Z', '丽': 'L', '咸': 'X',
        '宝': 'B', '克': 'K'
      };

      letter = pinyinMap[firstChar] || firstChar;
      
      if (!data[letter]) {
        data[letter] = [];
      }
      if (!data[letter].includes(city)) { // 避免重复添加
        data[letter].push(city);
      }
    });

    // 按字母排序
    const sortedData: { [key: string]: string[] } = {};
    Object.keys(data)
      .sort()
      .forEach(key => {
        sortedData[key] = data[key].sort(); // 对每个字母下的城市也进行排序
      });

    return sortedData;
  }, []);

  // 获取排序后的字母列表
  const letters = useMemo(() => Object.keys(cityData).sort(), [cityData]);

  // 处理搜索
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchText(e.target.value);
  };

  // 处理城市选择
  const handleCitySelect = (city: string) => {
    navigate('/zhi', { state: { selectedCity: city } });
  };

  // 过滤城市
  const getFilteredCities = () => {
    if (!searchText) return null;

    const result: string[] = [];
    const searchLower = searchText.toLowerCase();

    Object.values(cityData).forEach(cities => {
      cities.forEach(city => {
        if (city.toLowerCase().includes(searchLower)) {
          result.push(city);
        }
      });
    });

    return result;
  };

  const filteredCities = getFilteredCities();

  return (
    <div style={{ background: '#fff', minHeight: '100vh', fontFamily: 'sans-serif' }}>
      {/* 顶部导航栏 */}
      <div style={{ 
        padding: '16px', 
        borderBottom: '1px solid #eee', 
        display: 'flex', 
        alignItems: 'center',
        position: 'sticky',
        top: 0,
        background: '#fff',
        zIndex: 1
      }}>
        <button
          onClick={() => navigate(-1)}
          style={{ 
            background: 'none', 
            border: 'none', 
            fontSize: 20, 
            cursor: 'pointer',
            padding: '0 12px',
            color: '#333'
          }}
          aria-label="返回"
        >
          ←
        </button>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 18, fontWeight: 'bold' }}>
          选择城市
        </div>
      </div>

      {/* 搜索框 */}
      <div style={{ padding: '12px 16px', background: '#f5f5f5' }}>
        <div style={{ 
          display: 'flex', 
          alignItems: 'center',
          background: '#fff',
          borderRadius: 4,
          padding: '8px 12px'
        }}>
          <input
            value={searchText}
            onChange={handleSearch}
            placeholder="搜索城市"
            style={{
              flex: 1,
              border: 'none',
              fontSize: 14,
              outline: 'none'
            }}
          />
          {searchText && (
            <button
              onClick={() => setSearchText('')}
              style={{
                background: 'none',
                border: 'none',
                color: '#999',
                padding: '0 4px',
                cursor: 'pointer'
              }}
            >
              ×
            </button>
          )}
        </div>
      </div>

      {/* 当前定位城市 */}
      <div style={{ padding: '12px 16px' }}>
        <div style={{ color: '#999', fontSize: 14, marginBottom: 8 }}>当前定位城市：</div>
        <div style={{ 
          display: 'inline-block',
          padding: '8px 16px',
          background: '#f5f5f5',
          borderRadius: 4,
          fontSize: 14,
          cursor: 'pointer'
        }} onClick={() => handleCitySelect(currentCity)}>
          {currentCity}
        </div>
      </div>

      {!searchText ? (
        <>
          {/* 热门城市 */}
          <div style={{ padding: '12px 16px' }}>
            <div style={{ color: '#999', fontSize: 14, marginBottom: 8 }}>热门城市</div>
            <div style={{ 
              display: 'grid', 
              gridTemplateColumns: 'repeat(4, 1fr)', 
              gap: 8 
            }}>
              {hotCities.map((city, index) => (
                <div
                  key={index}
                  onClick={() => handleCitySelect(city)}
                  style={{
                    padding: '12px 0',
                    background: city === currentCity ? '#ff2d55' : '#f5f5f5',
                    color: city === currentCity ? '#fff' : '#333',
                    borderRadius: 4,
                    fontSize: 14,
                    textAlign: 'center',
                    cursor: 'pointer'
                  }}
                >
                  {city}
                </div>
              ))}
            </div>
          </div>

          {/* 字母索引城市列表 */}
          <div style={{ padding: '0 16px' }}>
            {letters.map(letter => (
              <div key={letter} id={letter} style={{ marginBottom: 16 }}>
                <div style={{ 
                  color: '#999', 
                  fontSize: 14, 
                  marginBottom: 8,
                  position: 'sticky',
                  top: 60,
                  background: '#fff',
                  padding: '4px 0'
                }}>
                  {letter}
                </div>
                <div style={{ 
                  display: 'grid', 
                  gridTemplateColumns: 'repeat(4, 1fr)', 
                  gap: 8 
                }}>
                  {cityData[letter].map((city, index) => (
                    <div
                      key={index}
                      onClick={() => handleCitySelect(city)}
                      style={{
                        padding: '12px 0',
                        background: city === currentCity ? '#ff2d55' : '#f5f5f5',
                        color: city === currentCity ? '#fff' : '#333',
                        borderRadius: 4,
                        fontSize: 14,
                        textAlign: 'center',
                        cursor: 'pointer'
                      }}
                    >
                      {city}
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </>
      ) : (
        // 搜索结果
        <div style={{ padding: '0 16px' }}>
          {filteredCities && filteredCities.length > 0 ? (
            filteredCities.map((city, index) => (
              <div
                key={index}
                onClick={() => handleCitySelect(city)}
                style={{
                  padding: '12px',
                  borderBottom: '1px solid #eee',
                  cursor: 'pointer'
                }}
              >
                {city}
              </div>
            ))
          ) : (
            <div style={{ 
              textAlign: 'center', 
              color: '#999', 
              padding: '32px 0' 
            }}>
              未找到相关城市
            </div>
          )}
        </div>
      )}

      {/* 字母索引条 */}
      {!searchText && (
        <div style={{ 
          position: 'fixed', 
          right: 4, 
          top: '50%', 
          transform: 'translateY(-50%)',
          display: 'flex',
          flexDirection: 'column',
          fontSize: 12,
          color: '#666'
        }}>
          {letters.map(letter => (
            <div
              key={letter}
              style={{
                padding: '2px 4px',
                cursor: 'pointer'
              }}
              onClick={() => {
                const element = document.getElementById(letter);
                if (element) {
                  element.scrollIntoView({ behavior: 'smooth' });
                }
              }}
            >
              {letter}
            </div>
          ))}
        </div>
      )}
    </div>
  );
} 